<template xmlns="">
  <div class="h-screen flex flex-col overflow-hidden">
    <!-- 导航栏...（保持原有不变） -->

    <main class="flex-1 container mx-auto px-4 py-2 overflow-hidden">
      <div class="flex gap-4 h-full">
        <!-- 新增左侧输入表单 -->
        <div class="w-1/3 flex flex-col bg-base-100 p-4 rounded-lg shadow-lg">
          <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-bold">行程需求定制</h2>
            <div class="flex-1 flex justify-end">  <!-- 新增这个容器使按钮靠右 -->
              <el-button
                  type="primary"
                  plain
                  size="default"
                  @click="goToHome"
              >
                回到首页
              </el-button>
              <hr>
            </div>
          </div>
          <el-form :model="formData" label-width="80px">
            <el-form-item label="出发地">
              <el-input v-model="formData.departure"/>
            </el-form-item>

            <el-form-item label="目的地">
              <el-input v-model="formData.destination"/>
            </el-form-item>

            <el-form-item label="出发时间" prop="departureDateTime">
              <el-date-picker
                  v-model="formData.departureDate"
                  type="datetime"
                  placeholder="请选择出发日期时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date(2000, 0, 1, 9, 0, 0)"
                  :editable="true"
                  :shortcuts="[
      {
        text: '今天09:00',
        value: () => {
          const date = new Date()
          date.setHours(9, 0, 0, 0)
          return date
        },
      },
      {
        text: '明天09:00',
        value: () => {
          const date = new Date()
          date.setDate(date.getDate() + 1)
          date.setHours(9, 0, 0, 0)
          return date
        },
      },
    ]"
              />
            </el-form-item>

            <el-form-item label="行程天数">
              <el-input-number
                  v-model="formData.days"
                  :min="1"
                  :max="15"
                  controls-position="right"
              />
            </el-form-item>

            <el-form-item label="预算范围">
              <el-input v-model="formData.budget" placeholder="例: 1000-1500"/>
            </el-form-item>

            <el-form-item label="兴趣类型">
              <el-select
                  v-model="formData.interests"
                  multiple
                  placeholder="请选择兴趣标签"
              >
                <el-option
                    v-for="item in ['自然风光', '历史文化', '美食体验', '户外活动', '亲子游乐']"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="交通方式">
              <el-select v-model="formData.transportation">
                <el-option
                    v-for="item in ['自驾', '高铁', '飞机', '大巴']"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="特殊要求">
              <el-input
                  v-model="formData.specialRequirements"
                  type="textarea"
                  :rows="2"
                  placeholder="例如：需要无障碍设施、包含餐饮等"
              />
            </el-form-item>

            <el-button
                type="primary"
                @click="connect"
                :disabled="isConnected"
                class="w-full"
            >
              生成智能行程
            </el-button>
<!--            !travelPlan.days.length-->
<!--            <el-button type="success" @click="savePlan" :disabled="isConnected">-->
<!--            保存行程-->
<!--            </el-button>-->
          </el-form>
        </div>

        <!-- 修改后的行程展示区域 -->
        <div class="w-2/3 flex flex-col bg-base-100 p-4 rounded-lg shadow-lg">
          <h2 class="text-xl font-bold mb-4">AI行程方案</h2>

          <div v-if="travelPlan.overview" class="mb-6">
            <h3 class="text-lg font-semibold mb-2">行程概览</h3>
            <div class="bg-base-200 p-4 rounded-lg">
              {{ travelPlan.overview }}
            </div>
          </div>

          <div v-for="day in travelPlan.days" :key="day.dayNumber" class="mb-6">
            <h3 class="text-lg font-semibold mb-2">第{{ day.dayNumber }}天</h3>

            <div class="grid grid-cols-2 gap-4">
              <div class="bg-base-200 p-4 rounded-lg">
                <h4 class="font-medium mb-2">上午安排</h4>
                <p class="text-sm opacity-75">🕒 {{ day.morning.time }}</p>
                <p class="mt-1">{{ day.morning.content }}</p>
              </div>

              <div class="bg-base-200 p-4 rounded-lg">
                <h4 class="font-medium mb-2">下午安排</h4>
                <p class="text-sm opacity-75">🕒 {{ day.afternoon.time }}</p>
                <p class="mt-1">{{ day.afternoon.content }}</p>
              </div>
            </div>

            <div class="mt-4 bg-base-200 p-4 rounded-lg">
              <h4 class="font-medium mb-2">住宿推荐</h4>
              <p>{{ day.hotel }}</p>
            </div>
          </div>

          <div v-if="travelPlan.budget" class="mt-6">
            <h3 class="text-lg font-semibold mb-2">预算分配</h3>
            <div
                class="bg-base-200 p-4 rounded-lg"
                v-html="marked.parse(travelPlan.budget)"
            />
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted, nextTick, watch} from 'vue'
import {marked} from 'marked'
import {ElMessage, ElLoading} from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router' // Add this import


const router = useRouter() // Add this line

// Add this function
const goToHome = () => {
  router.push('/')
}

// 修改后的SSE连接
const sseUrl = ref('http://localhost:8080/chat')
const messages = ref([])
const isConnected = ref(false)
const eventSource = ref(null)
const currentTheme = ref(localStorage.getItem('theme') || 'light')

// 新增用户输入表单
const formData = ref({
  departure: '昆明',
  destination: '大理',
  days: 3,
  departureDate: '',
  budget: '5000-8000',
  interests: ['自然风光', '历史文化'],
  transportation: '高铁',
  specialRequirements: '包含亲子活动'
})

// 生成结构化提示词模板
const generateStructuredPrompt = () => {
  return `请根据以下需求生成云南旅游行程：
【出发地】${formData.value.departure}
【目的地】${formData.value.destination}
【天数】${formData.value.departureDate}
【出发时间】${formData.value.days}天
【预算】${formData.value.budget}元
【兴趣】${formData.value.interests.join('、')}
【交通方式】${formData.value.transportation}
【特殊要求】${formData.value.specialRequirements}

请按照以下格式返回：
### 行程概览
{总览}

### 出发日期
{日期}

### 结束日期
{日期}

### 每日安排
#### 第{天数}天
**上午**
- 时间安排：{时间}
- 活动内容：{内容}
**下午**
- 时间安排：{时间}
- 活动内容：{内容}
**住宿推荐**
- {酒店信息}

### 预算分配
{详细预算}`.replace(/\n/g, '%0A') // URL编码换行符
}

// 修改后的SSE连接方法
const connect = () => {
  const prompt = generateStructuredPrompt()
  const fullUrl = `${sseUrl.value}?prompt=${encodeURIComponent(prompt)}`

  const loading = ElLoading.service({
    lock: true,
    text: 'AI正在生成行程，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  eventSource.value = new EventSource(fullUrl)

  eventSource.value.onmessage = (event) => {
    const parsed = parseSSEData(event.data)
    messages.value.push({
      time: new Date().toLocaleTimeString(),
      data: event.data,
      parsed
    })
  }

  const parseSSEData = (rawData) => {
    try {
      // 解析SSE数据格式（假设后端返回标准ChatCompletionResponse结构）
      const parsed = JSON.parse(rawData)
      return {
        content: parsed.choices?.[0]?.delta?.content || '', // 提取AI生成的内容片段
        index: parsed.choices?.[0]?.index || 0,          // 当前分片的序号
        finishReason: parsed.choices?.[0]?.finish_reason // 结束标识
      }
    } catch (error) {
      console.error('SSE数据解析失败:', error)
      return { content: '', index: 0, finishReason: null }
    }
  }

  eventSource.value.onerror = (error) => {
    loading.close()
    ElMessage.error('连接结束:' + error)
    disconnect()
  }

  eventSource.value.onopen = () => {
    isConnected.value = true
  }
}

// 新增行程解析方法
const parseTravelPlan = (content) => {
  const sections = content.split('### ')
  const result = {
    overview: '',
    days: [],
    budget: ''
  }

  sections.forEach(section => {
    if (section.startsWith('行程概览')) {
      result.overview = section.replace('行程概览\n', '').trim()
    } else if (section.startsWith('每日安排')) {
      const daysContent = section.replace('每日安排\n', '')
      result.days = parseDailySchedule(daysContent)
    } else if (section.startsWith('预算分配')) {
      result.budget = section.replace('预算分配\n', '').trim()
    }
  })

  return result
}

const parseDailySchedule = (content) => {
  const days = []
  const daySections = content.split('#### 第')

  daySections.slice(1).forEach(section => {
    const dayData = {
      dayNumber: 0,
      morning: {time: '', content: ''},
      afternoon: {time: '', content: ''},
      hotel: ''
    }

    const [header, ...rest] = section.split('**')
    dayData.dayNumber = parseInt(header.match(/\d+/)[0])

    rest.forEach(part => {
      if (part.startsWith('上午')) {
        const [, time, content] = part.match(/时间安排：(.+?)\s*活动内容：(.+)/s)
        dayData.morning = {time, content}
      } else if (part.startsWith('下午')) {
        const [, time, content] = part.match(/时间安排：(.+?)\s*活动内容：(.+)/s)
        dayData.afternoon = {time, content}
      } else if (part.startsWith('住宿推荐')) {
        dayData.hotel = part.replace('住宿推荐\n- ', '').trim()
      }
    })

    days.push(dayData)
  })

  return days
}

// 修改后的计算属性
const travelPlan = computed(() => {
  const fullContent = messages.value
      .filter(m => m.parsed?.content)
      .map(m => m.parsed.content)
      .join('')

  return parseTravelPlan(fullContent)
})

const disconnect = () => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
    isConnected.value = false
    ElMessage.success('生成完毕！')
  }
}

// 添加组件卸载时的清理
onUnmounted(() => {
  disconnect()
})

const savePlan = async () => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'));
    if (!currentUser?.user_id) {
      ElMessage.error('用户信息未找到，请重新登录');
      return;
    }

    // 验证必填字段
    if (!formData.value.departureDate) {
      ElMessage.error('请选择出发日期');
      return;
    }

    // 计算日期范围
    const startDate = new Date(formData.value.departureDate);
    const endDate = new Date(startDate);
    endDate.setDate(startDate.getDate() + formData.value.days - 1);

    // 格式化为符合后端的日期时间字符串
    const startTime = `${formData.value.departureDate} 09:00:00`;
    const endTime = `${endDate.toISOString().split('T')[0]} 18:00:00`;

    // 构建符合DTO结构的数组
    const payloads = travelPlan.value.days.map(day => ({
      day_number: day.dayNumber,
      start_time: startTime,
      end_time: endTime,
      departure:  formData.value.departure,
      destination: formData.value.destination,
      duration_days: formData.value.days,
      budget_range: formData.value.budget,
      status: 1,
      generated_by: 'AI',
      user_id: currentUser.user_id,
      morning_activity: day.morning.content,
      afternoon_activity: day.afternoon.content,
      hotel_recommendation: day.hotel,
      overview: travelPlan.value.overview,
      budget_allocation: travelPlan.value.budget
    }));

    // 调用批量插入接口
    await axios.post(`${BASE_URL}/itinerary-details/batch-insert`, payloads);
    ElMessage.success('行程保存成功');
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error(error.response?.data?.msg || '保存失败，请检查数据');
  }
};
</script>

<style scoped>

.flex.justify-end {
  margin-right: auto;
}

.flex.justify-between {
  align-items: center;
}

.grid {
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}

.el-form-item:deep(.el-form-item__label) {
  @apply text-gray-700 font-medium;
}

.el-select:deep(.el-select__tags) {
  @apply flex-wrap;
}
</style>